package com.hulman.oms.dao;

import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Repository
@Slf4j
public class MiniProgramDao
{
    @Value("${wx.corp-id:}")
    private String corpId;
    @Value("${wx.mini-program.secret:}")
    private String secret;
    @Value("${wx.mini-program.agent-id:}")
    private String agentId;
    @Value("${wx.mini-program.app-id:}")
    private String appId;
    @Autowired
    private RestTemplate restTemplate;

    public boolean isMiniProgramEnabled()
    {
        return !StringUtil.isEmpty(corpId) && !StringUtil.isEmpty(secret) && !StringUtil.isEmpty(agentId) && !StringUtil.isEmpty(appId);
    }

    public String getAccessToken()
    {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={1}&corpsecret={2}";
        Map<String, Object> result = restTemplate.getForObject(url, Map.class, corpId, secret);
        log.info("corpId:{}", corpId);
        Integer errCode = (Integer) result.get("errcode");
        String accessToken = (String) result.get("access_token");
        if (errCode == 0 && !StringUtil.isEmpty(accessToken))
        {
            return accessToken;
        } else
        {
            log.error("result:{}", result);
            throw new IoTException("无法获取有效的accessToken");
        }
    }

    public String code2Session(String accessToken, String code)
    {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token={1}&js_code={2}&grant_type=authorization_code";
        Map<String, Object> result = restTemplate.getForObject(url, Map.class, accessToken, code);
        System.out.println(result);
        Integer errCode = (Integer) result.get("errcode");
        String errMsg = (String) result.get("errmsg");
        String userId = (String) result.get("userid");
        if (errCode != 0)
        {
            throw new IoTException(errMsg);
        } else
        {
            return userId;
        }
    }

    public void sendMiniprogram(String accessToken, String userIds, String title, String description, String page, Map<String, String> items)
    {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={1}";
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("touser", userIds);
        map.put("msgtype", "miniprogram_notice");
        Map<String, Object> notice = new HashMap<>();
        notice.put("appid", appId);
        notice.put("page", page);
        notice.put("title", StringUtil.padRight(title, ' ', 4));
        notice.put("description", description);
        log.info("notice:{}",notice);
        //notice.put("emphasis_first_item", true);
        List<Map<String, String>> contentItems = new ArrayList<>();
        for (Map.Entry<String, String> entry : items.entrySet())
        {
            Map<String, String> item = new HashMap<>();
            item.put("key", entry.getKey());
            item.put("value", entry.getValue());
            contentItems.add(item);
        }
        notice.put("content_item", contentItems);
        map.put("miniprogram_notice", notice);
        log.info("mini app post:{}", map);
        Map<String, Object> result = restTemplate.postForObject(url, map, Map.class, accessToken);
        log.info("mini app result:{}", result);
        Integer errCode = (Integer) result.get("errcode");
        String errMsg = (String) result.get("errmsg");
        if (errCode != 0)
        {
            throw new IoTException(errMsg);
        }
    }
}
